<template>
    <div id="terminal"/>
</template>

<script>
import 'xterm/css/xterm.css';
import {Terminal} from 'xterm';
import {FitAddon} from "xterm-addon-fit";
import {AttachAddon} from 'xterm-addon-attach';

export default {
    name: 'HelloWorld',
    props: {
        msg: String
    },
    mounted() {
        // Terminal
        var terminal = new Terminal({
            cursorBlink: true,
            cursorStyle: "underline", //光标样式
            convertEol: true
        });

        const clientId = 'Q2LnhojsDN7koghqVLoOxRotx9SYRhqP';
        const subProtocols = [clientId, '333333']

        // WebSocket
        const socket = new WebSocket('ws://192.168.10.10:7681?dev=123456789', subProtocols);
        const attachAddon = new AttachAddon(socket); // 建立websocket链接
        terminal.loadAddon(attachAddon);

        const fitAddon = new FitAddon();
        terminal.loadAddon(fitAddon)

        terminal.open(document.getElementById('terminal'));

        let inputBuffer = ''; //
        terminal.onData(data => {
        	console.log('\\x' + data.charCodeAt().toString(16))
        	if (data === '\r') {
        		// terminal.writeln(`\r\nYou typed: ${inputBuffer}`);
        	  socket.send(JSON.stringify({"clientId":clientId, "type":'GATE_DEBUG', "data":inputBuffer}))
        		inputBuffer = '';
        		terminal.writeln('');
        	}
        	//
        	else if (data === '\x7f') { // '\x7f' ASCII
        		inputBuffer = inputBuffer.slice(0, -1); //
        		terminal.write('\b \b'); //
        	}
        	//
        	else {
        		inputBuffer += data; //
        		terminal.write(data); //
        	}
        });

        window.onresize = function() {
            // 窗口尺寸变化时，终端尺寸自适应
            fitAddon.fit()
        }

        terminal.focus();

        this.term = terminal
        this.socket = socket
    },
    beforeUnmount() {
        this.socket.close()
        this.terminal.dispose()
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
    margin: 40px 0 0;
}
ul {
    list-style-type: none;
    padding: 0;
}
li {
    display: inline-block;
    margin: 0 10px;
}
a {
    color: #42b983;
}
</style>
